var express = require('express');
var router = express.Router();
var axios = require('axios');
var md5 = require('md5');
var base64 = require('base-64');
var utf8 = require('utf8');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Expressaaa' });
});
/*
router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})
*/



function toDub(n) { return n < 10 ? '0' + n : n }

//当前时间yyyyMMddHHmmss
function getTimeStr() {
    var date = new Date();
    return date.getFullYear().toString() + toDub(date.getMonth() + 1) + toDub(date.getDate()) + toDub(date.getHours()) + toDub(date.getMinutes()) + toDub(date.getSeconds());
}

router.post('/add', function(req, res, next) {
    var param = req.body.code; //短信验证码
    var to = req.body.phone; //需要发送的号码
    var appId = '2c96f9979933494499b4f69486b3ae3d';
    var templateId = 134307;
    var SoftVersion = '2014-06-30';
    var AccountSid = '2c2444f03ce460e03190ff47665e0cde';
    var token = '9073f8af7042446bb7c063b69f8238f2';
    var baseURL = 'https://api.ucpaas.com/';
    var timeStr = getTimeStr();
    var SigParameter = md5(AccountSid + token + timeStr).toUpperCase();
    // 使用MD5加密（账户Id + 账户授权令牌 + 时间戳），共32位。
    // token = '9073f8af7042446bb7c063b69f8238f2'

    var bytes = utf8.encode(AccountSid + ':' + timeStr);
    var Authorization = base64.encode(bytes);
    // Authorization 使用Base64编码（账户Id + 冒号 + 时间戳） 

    // 时间戳 new Date().getTime()
    // (AccountSid+token+时间戳)
    // 
    var url = `${baseURL}/${SoftVersion}/Accounts/${AccountSid}/Messages/templateSMS/?sig=${SigParameter}`;

    //https://api.ucpaas.com/2014-06-30/Accounts/2c2444f03ce460e03190ff47665e0cde/Messages/templateSMS?sig=5706E3E3FB1CF607E675E4C8EB984F6B


    // {SoftVersion}/Accounts/{AccountSid}/{function}/{operation}?sig={SigParameter}
    axios({
        method: 'post',
        url: url,
        data: {
            templateSMS: {
                appId: appId,
                param: param,
                templateId: templateId,
                to: to
            }
        },
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json",
            "Authorization": Authorization
        }
    }).then(function(response) {
        console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
        // console.log(response);
        console.log(response.data);
        res.json(response)
        console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    }, function(err) {
        console.log(err)
    });

});



module.exports = router;